package com.xwj.Interceptor;

import com.xwj.data.StaticData;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 前台访问拦截器
 */
@Component
public class FrontHandlerInterceptor implements HandlerInterceptor {
    /**
     * Controller执行之前调用
     *
     * @param httpServletRequest
     * @param httpServletResponse
     * @param o
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        ServletContext context = httpServletRequest.getServletContext();
        String accountid = (String) context.getAttribute(StaticData.REGISTER_USER_LOGIN_ATTRIBUTE);
        if (StringUtils.isBlank(accountid)) {
            httpServletResponse.sendRedirect("/front/login/loginView");
            return false;
        }
        return true;
    }

    /**
     * Controller执行之后，页面渲染之前调用
     *
     * @param httpServletRequest
     * @param httpServletResponse
     * @param o
     * @param modelAndView
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    /**
     * 页面渲染之后，一般用于资源清理
     *
     * @param httpServletRequest
     * @param httpServletResponse
     * @param o
     * @param e
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}
